package org.jeecg.modules.quartz.job;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import org.jeecg.common.nc.enums.WSEnum;
import org.jeecg.common.nc.service.NCWebService;
import org.jeecg.common.nc.vo.WSVO;
import org.jeecg.modules.nc.entity.NcBdTaxcode;
import org.jeecg.modules.nc.entity.NcOrg;
import org.jeecg.modules.nc.service.INcBdTaxcodeService;
import org.jeecg.modules.quartz.entity.TbJobLog;
import org.jeecg.modules.quartz.service.IQuartzJobService;
import org.jeecg.modules.quartz.service.ITbJobLogService;
import org.jeecg.modules.system.service.impl.SysDepartServiceImpl;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: wjb
 * @Date: 2021/12/20/0:06
 * @Description:
 */
public class NCTaxCodeSyncJob implements Job {

    private static final Logger logger = LoggerFactory.getLogger(NCUserSyncJob.class);

    @Autowired
    IQuartzJobService jobService;

    @Autowired
    private ITbJobLogService tbJobLogService;

    @Autowired
    private INcBdTaxcodeService ncBdTaxcodeService;

    @Autowired
    SysDepartServiceImpl sysDepartService;

    @Value("${qixin.ncserver.uri}")
    private String NC_SERVER_URI;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String lastTime = jobService.queryLastTime("nctaxcodesyncjob");
        String currentTime = DateUtil.now();
        Boolean first = false;
        if (StrUtil.isBlank(lastTime)){
            lastTime = "2008-01-01 00:00:00";
            first = true; // 表示第一次同步
        }

        try{
            // 获取组织个数
            List<NcOrg> ncOrgs = sysDepartService.querOrgList();
            WSVO vo = new WSVO();
            if(ncOrgs.size() > 0){
                for (NcOrg ncOrg:ncOrgs) {
                    WSEnum.TAXCODE.setMsg(ncOrg.getCode());
                    vo = NCWebService.getFromWS(NC_SERVER_URI, WSEnum.TAXCODE,lastTime);
                    for (Map<String, Object> map : vo.getContent()) {
                        NcBdTaxcode ncBdTaxcode = new NcBdTaxcode();
                        // 主表
                        Map<String,Object> headMap = (Map<String, Object>) map.get("head");
                        ncBdTaxcode.setId((String) headMap.get("pk_taxcode")); //税码主键
                        ncBdTaxcode.setCode((String) headMap.get("code")); //税码
                        ncBdTaxcode.setDescription((String) headMap.get("description")); //描述
                        ncBdTaxcode.setEnablestate((Integer) headMap.get("enablestate")); //启用状态：1=未启用，2=已启用，3=已停用
                        ncBdTaxcode.setPkGroup((String) headMap.get("pk_group")); // 所属集团
                        ncBdTaxcode.setPkOrg((String) headMap.get("pk_org")); // 所属组织

                        // 子表
                        List<Map<String,Object>> bodyList = new ArrayList<>();
                        bodyList = (List<Map<String,Object>>)map.get("body");
                        if(bodyList.size() > 0 ){
                            for (Map bodyMap:bodyList) {
                                ncBdTaxcode.setPkTaxrate((String) bodyMap.get("pk_taxrate")); // 税率主键
                                if(bodyMap.get("realtaxrate")!=null){
                                    ncBdTaxcode.setRealtaxrate(new BigDecimal(bodyMap.get("realtaxrate").toString())); // 不可抵扣税率
                                }
                                if(bodyMap.get("taxrate")!=null){
                                    ncBdTaxcode.setTaxrate(new BigDecimal(bodyMap.get("taxrate").toString()) ); // 税率
                                }
                                ncBdTaxcode.setTaxtype((Integer) bodyMap.get("taxtype")); // 扣税类别：1=应税外加，0=应税内含
                                ncBdTaxcode.setDr((Integer) bodyMap.get("dr")); // 扣税类别：1=应税外加，0=应税内含
                            }
                        }
                        ncBdTaxcodeService.saveOrUpdate(ncBdTaxcode);
                    }
                    TbJobLog tbJobLog = new TbJobLog();
                    tbJobLog.setName(ncOrg.getName()+"NC税率同步");
                    tbJobLog.setContent(ncOrg.getName()+"本次新增或更新记录" + vo.getContent().size() + "条");
                    tbJobLog.setNum(vo.getContent().size());
                    tbJobLogService.save(tbJobLog);
                    }
                if (first) {
                    // 新增一条记录
                    jobService.insetLastTime("nctaxcodesyncjob", currentTime);
                } else {
                    //更新最后同步时间
                    jobService.updateLastTime("nctaxcodesyncjob", currentTime);
                }
                logger.info("NC税率同步成功更新：{}条", vo.getContent().size());
            }

        }catch (Exception e){
            logger.info("NC税率同步出现异常：{}", e.getMessage());
            e.printStackTrace();
            TbJobLog tbJobLog = new TbJobLog();
            tbJobLog.setName("NC税率同步");
            tbJobLog.setContent("同步出现异常：" + e.getMessage());
            tbJobLog.setNum(0);
            tbJobLogService.save(tbJobLog);
        }
    }
}
